package com.example.demo.web.api

import com.example.demo.data.Taco
import com.example.demo.data.repository.TacoRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.data.rest.webmvc.RepositoryRestController
import org.springframework.hateoas.CollectionModel
import org.springframework.hateoas.EntityModel
import org.springframework.hateoas.PagedModel
import org.springframework.hateoas.server.EntityLinks
import org.springframework.hateoas.server.RepresentationModelProcessor
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping

@RepositoryRestController
class RecentTacosController @Autowired constructor(
        private val tacoRepo: TacoRepository
)  {

//    @Bean
//    fun tacoProcessor(links: EntityLinks): RepresentationModelProcessor<PagedModel<EntityModel<Taco>>> {
//        return RepresentationModelProcessor { model ->
//            model.add(
//                    links.linkFor(Taco::class.java)
//                            .slash("recent")
//                            .withRel("recents")
//            )
//            model
//        }
//    }


    @GetMapping(path = ["/tacos/recent"], produces = ["application/hal+json"])
    fun recentTacos(): ResponseEntity<CollectionModel<TacoResource>> {

        val pageRequest = PageRequest.of(0, 2, Sort.by("createdAt").descending())
        val tacos = tacoRepo.findAll(pageRequest)

        val tacoResources = TacoResourceAssembler().toCollectionModel(tacos)

        val recentResources = CollectionModel.of(tacoResources)
        recentResources.add(
                WebMvcLinkBuilder.linkTo(
                        WebMvcLinkBuilder.methodOn(RecentTacosController::class.java).recentTacos()
                )
                        .withRel("recents")
        )
        return ResponseEntity(recentResources, HttpStatus.OK)
    }
}